package com.sdk.business.impl;

import com.sdk.business.SessionService;
import com.sdk.cache.InMemoryCache;
import com.sdk.exception.CustomException;
import com.sdk.utils.SessionGenUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author llnf
 */
public class SessionServiceImpl implements SessionService {

  private final InMemoryCache<String, String> sessionCache;

  private final ScheduledExecutorService scheduler;

  public SessionServiceImpl(InMemoryCache<String, String> sessionCache) {
    this.sessionCache = sessionCache;
    this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "CleanExpiredCacheThread"));
  }


  @Override
  public void startCleanupScheduler() {
    // Schedule cleanup task to run every 30 seconds
    scheduler.scheduleAtFixedRate(sessionCache::cleanupExpiredEntries, 30, 30, TimeUnit.SECONDS);
  }

  @Override
  public void stopCleanupScheduler() {
    scheduler.shutdown();
    try {
      if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
        scheduler.shutdownNow();
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new CustomException();
    }
  }


  @Override
  public String createSession(String customerId) {
    return sessionCache.computeIfAbsent(customerId, key -> SessionGenUtils.getSessionId(), 600);
  }

  @Override
  public String getCustomerId(String sessionKey) {
    return sessionCache.getKeyByCacheValue(sessionKey);
  }

}
